import './login.scss'
import { Slider, Input, message, ConfigProvider, Tooltip } from 'antd'
import { useEffect, useState } from 'react'
import SvgIcon from '@/components/SvgIcon'
import { useNavigate } from 'react-router-dom'
import { reqGetCode, reqLogin } from '@/api/user'
import { useDispatch } from 'react-redux'
import { UserActions } from '@/store'
import { getTime } from '@/utils/time'

function Login() {
  const dispatch: any = useDispatch()
  // 使用 useNavigate 钩子进行路由跳转
  const navigate = useNavigate()
  // 定义响应式数据
  const [open, setOpen] = useState(false)
  const [show, setShow] = useState(0)
  const [email, setEmail] = useState('')
  const [code, setCode] = useState('')
  const [storeCode, setStoreCode] = useState('')
  const [tipsEmail, setTipsEmail] = useState('')
  const [tipsCode, setTipsCode] = useState('')
  const [slider, setSlider] = useState(false)

  // 监听esc事件，用来关闭对话框
  document.onkeydown = (e) => {
    e.key === 'Escape' ? closeModal() : false
  }
  // 数据重置
  const cleanData = () => {
    setShow(0)
    setEmail('')
    setCode('')
    setTipsEmail('')
    setTipsCode('')
    setSlider(false)
  }

  // 打开对话框
  const openModal = () => {
    setOpen(true)
    cleanData()
  }

  // 关闭对话框
  const closeModal = () => {
    setOpen(false)
  }

  // 点击返回首页的触发事件
  const backToHome = () => {
    navigate('/')
  }

  // 判断滑块是否滑到底
  const handleSlider = (num: number) => {
    num === 100 ? setShow(2) : null
  }

  // 邮箱输入框的输入触发事件
  const emailChange = (e: any) => {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    const val = e.target.value
    setEmail(val)
    if (!val) {
      setTipsEmail('邮箱不能为空')
    } else if (!emailRegex.test(val)) {
      setTipsEmail('请输入有效的邮箱地址')
    } else {
      setTipsEmail('')
      setSlider(true)
    }
  }

  // 验证码输入框的输入触发事件
  const codeChange = (e: any) => {
    const val = e.target.value
    setCode(val)
    if (!val) {
      setTipsCode('验证码不能为空')
    } else {
      setTipsCode('')
    }
  }

  // 邮箱输入框失焦触发事件
  const emailBlur = () => {
    slider && setShow(1)
  }

  // 发送邮箱验证码
  const getCode = async () => {
    const res = await reqGetCode({ email })
    if (res.code === 200) {
      setStoreCode(res.data)
    }
  }

  // 用户登录
  const userLogin = async () => {
    const res = await reqLogin({ email })
    if (res.code === 200) {
      localStorage.setItem('token', JSON.stringify(res.data))
      dispatch(UserActions.changeToken(res.data))
      navigate('/main')
      message.success(`${getTime()}好，欢迎使用慧教云！`)
    }
  }

  useEffect(() => {
    openModal()
  }, [])

  useEffect(() => {
    show === 2 && getCode()
  }, [show])

  const handleLogin = () => {
    if (email && code && code === storeCode) {
      userLogin()
    } else {
      message.error('请输入正确的邮箱和验证码')
    }
  }

  return (
    <div className="Login">
      <div className="container">
        <Tooltip
          placement="right"
          color="#fff"
          title={
            <span style={{ color: '#000', fontSize: '14px', cursor: 'default' }}>返回首页</span>
          }
        >
          <div onClick={backToHome} className="logo-back">
            <img style={{ width: 'auto', height: '50px' }} src="/assets/images/font.png" alt="" />
            <p>慧教云</p>
          </div>
        </Tooltip>
      </div>
      <div className={`modal ${open ? 'is-open' : ''}`}>
        <div className="modal-container">
          <div className="modal-left">
            <div className="header">
              <div className="logo">
                <img
                  style={{ width: 'auto', height: '50px' }}
                  src="/assets/images/font.png"
                  alt=""
                />
                <p>慧教云</p>
              </div>
              <p className="modal-desc">欢迎体验智能测评系统！</p>
            </div>
            <div className="body">
              <div className="input-body">
                <div className="input-block">
                  <label htmlFor="email" className="input-label">
                    邮箱
                  </label>
                  <Input
                    onBlur={emailBlur}
                    onChange={emailChange}
                    type="email"
                    name="email"
                    id="email"
                    value={email}
                    placeholder="Email"
                  />
                </div>
                <p className="tips">{tipsEmail}</p>
              </div>
              {(show === 1 && (
                <div className="slider">
                  <p className="slider-getcode">滑动获取邮箱验证码</p>
                  <ConfigProvider
                    theme={{
                      components: { Slider: { railSize: 20, handleSize: 20, handleSizeHover: 20 } },
                    }}
                  >
                    <Slider
                      onChange={handleSlider}
                      tooltip={{
                        open: false,
                      }}
                    />
                  </ConfigProvider>
                </div>
              )) ||
                (show === 2 && (
                  <div className="input-body">
                    <div className="input-block">
                      <label htmlFor="code" className="input-label">
                        验证码
                      </label>
                      <Input
                        onChange={codeChange}
                        type="code"
                        name="code"
                        id="code"
                        onKeyUp={(e) => {
                          e.key === 'Enter' && handleLogin()
                        }}
                        placeholder="Verification code"
                      />
                    </div>
                    <p className="tips">{tipsCode}</p>
                  </div>
                ))}
            </div>
            <div className="modal-buttons">
              <p>如果未注册则直接注册</p>
              <button onClick={handleLogin} className="input-button">
                登录
              </button>
            </div>
          </div>
          <div className="modal-right">
            <img src="/assets/images/dialogBg.avif" alt="" />
          </div>
          <button onClick={closeModal} className="icon-button close-button">
            <SvgIcon name="cancel" size="20px" />
          </button>
        </div>
        <button onClick={openModal} className="modal-button">
          立即登录
        </button>
      </div>
    </div>
  )
}

export default Login
